package com.example.kiratest.notify;

import com.alibaba.fastjson.JSON;
import com.example.kiratest.notify.Util.SmartHttpUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Slf4j
@Setter
@Component
/**
 * 获取Token然后发起请求
 */
//我们首先通过getToken()来获取我们的Token，然后调用SmartHttpUtil里的postWithHeade()方法来发起请求
public class DingtalkNotifier implements Notifier {


    private String appkey="dingzrr5q24mlutd6knl";
    private String appsecret="C2vkXuTegyUNsmftSKRgO4zq0lRuLBbw2oxxB_A_vzc0T0LHcsR2FxH3atMLDrlT";

    private String dingTalkTokenUrl = "https://oapi.dingtalk.com/gettoken";
    private String dingTalkSendUrl = "https://api.dingtalk.com/v1.0/card/instances/createAndDeliver";

    @Override
    public T notify(String message,Integer msgType) {

        try {
            Map<String, String> headers = Map.of("x-acs-dingtalk-access-token", getToken());
            log.info("开始发送请求");
            String s = SmartHttpUtil.postWithHeader(dingTalkSendUrl, message, headers);
            System.out.println(s);
        } catch (Exception e) {
            log.error("==== feishu notify ==== execute err:", e);
        }
        return null;
    }

    //根据appKey和appsecret来拿到我们的dingtalk平台的token
    private String getToken(){
        try {
            String jsonResponse = SmartHttpUtil.get(UriComponentsBuilder.fromHttpUrl(dingTalkTokenUrl)
                                                .queryParam("appkey", appkey)
                                                .queryParam("appsecret", appsecret)
                                                .toUriString());
            String accessToken = JSON.parseObject(jsonResponse).getString("access_token");
            log.info("Token:{}",accessToken);
            return accessToken;
        } catch (Exception e) {
            log.error("==== feishu notify ==== execute err:", e);
        }
        return null;
    }

}
